text = "Python编程很有趣"

# 基本切片 [start:end:step]
print(text[0:6])      # "Python"（0到5索引）
print(text[6:])       # "编程很有趣"（从索引6到末尾）
print(text[:6])       # "Python"（开头到索引5）
print(text[::2])      # "Pto编趣"（步长2）
print(text[::-1])     # "趣很辑编nohtyP"（反转字符串）

# 实用场景：提取手机号前3位和后4位
phone = "13812345678"
print(f"运营商号段: {phone[:3]}, 尾号: {phone[-4:]}")
# 输出：运营商号段: 138, 尾号: 5678






# 基本分割
csv_data = "苹果,香蕉,橙子,西瓜"
fruits = csv_data.split(",")
print(fruits)  # ['苹果', '香蕉', '橙子', '西瓜']

# 限制分割次数
log = "2023-08-20 14:30:25 [INFO] 用户登录成功"
parts = log.split(" ", 2)  # 只分割前2次
print(parts)  # ['2023-08-20', '14:30:25', '[INFO] 用户登录成功']

# 多分隔符分割（需用re模块）
import re
text = "苹果;香蕉,橙子|西瓜"
print(re.split(r"[;,]|\|", text))  # ['苹果', '香蕉', '橙子', '西瓜']















# 列表转字符串
words = ["Hello", "world", "!"]
print(" ".join(words))  # "Hello world !"

# 路径拼接（比+更高效）
path_parts = ["C:", "Users", "Alice", "file.txt"]
print("\\".join(path_parts))  # "C:\Users\Alice\file.txt"

# 生成SQL条件
conditions = ["age > 18", "gender = 'M'", "status = 1"]
sql = "SELECT * FROM users WHERE " + " AND ".join(conditions)
print(sql)  # SELECT * FROM users WHERE age > 18 AND gender = 'M' AND status = 1









# 基本去空格
user_input = "   some text   "
print(f"|{user_input.strip()}|")  # "|some text|"

# 去除特定字符
code = ">>>print('hello')<<<"
print(code.strip("><"))  # "print('hello')"

# 处理CSV数据
dirty_data = ",,value1, value2 ,value3,,"
clean_data = [x.strip() for x in dirty_data.split(",") if x.strip()]
print(clean_data)  # ['value1', 'value2', 'value3']







name = "Alice"
age = 25
score = 95.5678

# 基础用法
print(f"{name}今年{age}岁")  # Alice今年25岁

# 数字格式化
print(f"分数: {score:.1f}")    # 分数: 95.6（保留1位小数）
print(f"十六进制: {age:#x}")    # 十六进制: 0x19
print(f"百分比: {0.25:.2%}")   # 百分比: 25.00%

# 对齐文本
print(f"姓名: {name:<10}")     # 左对齐（姓名: Alice     ）
print(f"年龄: {age:^10}")      # 居中对齐（年龄:     25    ）
print(f"分数: {score:>10.2f}") # 右对齐（分数:      95.57）

# 表达式计算
print(f"明年年龄: {age + 1}")  # 明年年龄: 26

# 调用方法
print(f"大写名字: {name.upper()}")  # 大写名字: ALICE

# 字典取值
user = {"name": "Bob", "age": 30}
print(f"用户: {user['name']}, 年龄: {user['age']}")  # 用户: Bob, 年龄: 30

























log_line = "2023-08-20 14:30:25 [ERROR] 文件未找到: /path/to/file"
# 使用split和切片提取关键信息
date = log_line[:10]
time = log_line[11:19]
level, message = log_line[21:].split("] ", 1)
print(f"""
时间: {time}
级别: {level[1:]}
信息: {message}\
""")




data = [
    ["Python", "3.10", "2021"],
    ["Java", "17", "2021"],
    ["C++", "20", "2020"]
]

# 计算每列最大宽度
col_widths = [
    max(len(item) for item in col)
    for col in zip(*data)
]

# 生成表格
header = ["语言", "版本", "发布年"]
divider = "+".join(["-" * (w + 2) for w in col_widths])
print(f"| {' | '.join(h.ljust(w) for h, w in zip(header, col_widths))} |")
print(divider)
for row in data:
    print(f"| {' | '.join(item.ljust(w) for item, w in zip(row, col_widths))} |")






import re
from collections import Counter

def word_count(text):
    """统计文本中单词出现频率"""
    # 使用正则表达式分割单词（忽略标点）
    words = re.findall(r'\b\w+\b', text.lower())  # \b表示单词边界，\w匹配字母数字下划线
    return Counter(words)  # 返回计数器对象

# 示例文本
sample_text = """
Python is powerful, and Python is fast. 
It's also easy to learn! Python 3.10 released in 2021.
"""

# 统计并展示结果
counts = word_count(sample_text)
print("单词频率统计:")
for word, freq in counts.most_common():  # 按频率降序排列
    print(f"{word}: {freq}次")

# 扩展：统计字符频率
char_counts = Counter(sample_text.lower())
print("\n字符频率TOP5:")
for char, count in char_counts.most_common(5):
    print(f"'{char}': {count}次")



























def validate_password(password):
    """验证密码强度"""
    strength = {
        'length': len(password) >= 8,
        'has_upper': any(c.isupper() for c in password),
        'has_lower': any(c.islower() for c in password),
        'has_digit': any(c.isdigit() for c in password),
        'has_special': not password.isalnum()  # 包含特殊字符
    }

    # 计算强度得分
    score = sum(strength.values())

    # 返回结果
    feedback = []
    if not strength['length']:
        feedback.append("密码长度至少8位")
    if not strength['has_upper']:
        feedback.append("需要包含大写字母")
    if not strength['has_lower']:
        feedback.append("需要包含小写字母")
    if not strength['has_digit']:
        feedback.append("需要包含数字")
    if not strength['has_special']:
        feedback.append("建议添加特殊字符")

    return {
        'is_valid': score >= 4,  # 满足4条规则算合格
        'score': f"{score}/5",
        'feedback': feedback
    }


# 测试用例
passwords = ["abc123", "Python3", "Strong@Pass123", "弱密码"]
for pwd in passwords:
    result = validate_password(pwd)
    print(f"\n密码: {pwd}")
    print(f"强度: {result['score']} | 有效性: {'通过' if result['is_valid'] else '不通过'}")
    if result['feedback']:
        print("改进建议:")
        for tip in result['feedback']:
            print(f"- {tip}")







# 安装：pip install jieba
import jieba

text = "自然语言处理是人工智能的重要方向"
words = jieba.lcut(text)  # 精确模式分词
print("中文分词结果:", "/".join(words))  # 输出：自然/语言/处理/是/人工智能/的/重要/方向




import random
import string

def generate_password(length=12):
    """生成随机强密码"""
    chars = (
        string.ascii_uppercase +
        string.ascii_lowercase +
        string.digits +
        "!@#$%^&*"
    )
    while True:
        pwd = ''.join(random.choice(chars) for _ in range(length))
        if validate_password(pwd)['is_valid']:
            return pwd

print("生成强密码:", generate_password())
# 示例输出：生成强密码: 7D$k9Lp@2xYv